/*
Copyright (C) 2009-2010 Xanadu Development Team

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; version 2
of the License.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

#include "../provider/DataProvider.h"
#include "../client/MapData.h"
#include "Player.h"
#include "PlayerBuffs.h"
#include "MapPlayers.h"
#include "Event.h"
#include "../client/MapsData.h"
#include "../tools/PacketCreator.h"
#include "Map.h"
#include "../tools/Tools.h"
#include "PlayerBuffs.h"
#include "../client/MapShipData.h"

void MapPlayers::add(Player* player) {
	players[player->getID()] = player;
	if (!player->getBuffs()->isBuffActive(9101004)) {
		playersv.push_back(player);
		map->send(PacketCreator().showPlayer(player));
	} else {
		player->send(PacketCreator().beginHide());
	}
	for(int i=0; i<(int)playersv.size(); i++){
		if(playersv[i] != player)
			player->send(PacketCreator().showPlayer(playersv[i]));
	}
	if(map->getEvent() != 0) {
		send(PacketCreator().showTimer(map->getEvent()->getTime()));
	}
	if(map->getMusic() != MapsData::getInstance()->getDataByID(map->getID())->getMusic()) {
		player->send(PacketCreator().changeMusic(map->getMusic()));
	}
	if(map->getType() == 2){
		MapShipData * shipData = MapsData::getInstance()->getDataByID(map->getID())->getShip();
		if(shipData !=0){
			player->send(PacketCreator().showShip((shipData->getType() == 0) ? (map->getShip() ? 1 : 3) : 4, (shipData->getType() == 0) ? 0 : 1));
/*			if(ship->getType() == 0)
				player->send(PacketCreator().showShip(map->getShip() ? 1 : 3, 0));
			else{
				if(map->getShip()){
					player->send(PacketCreator().showShip(4, 1));
				}
			}*/
		}
	}
	if(MapsData::getInstance()->getDataByID(map->getID())->getClock()){
		player->send(PacketCreator().showClock(Tools::getTime()));
	}
}

void MapPlayers::remove(Player* player){
	if (player->getPvP() && map->getPvP() != 0)
		map->send(PacketCreator().stopPvP(player), player);
	if(players.find(player->getID()) != players.end()){
		players.erase(player->getID());
	}
	for(int i=0; i<(int)playersv.size(); i++){
		if(playersv[i] == player){
			playersv.erase(playersv.begin()+i);
			break;
		}
	}
	map->send(PacketCreator().removePlayer(player));
}